package com.igeek.handler;

import com.igeek.entity.Department;
import com.igeek.json.JsonResult;
import com.igeek.redis.RedisUtil;
import com.igeek.service.DepService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("dep")
public class DepartmentHandler {

    @Resource
    private DepService depService;

    @Resource
    private RedisUtil redisUtil;

    @GetMapping("all")
    public JsonResult findAll(){
        List<Department> list = null;
        //从缓存中进行调用
        Object object = redisUtil.get("depList");
        if(object != null){
            System.out.println("从缓存中查到的部门数据");
            list = (List<Department>) object;
        }
        //如果缓存中没有找到，则查询数据库
        else{
            //查询所有部门
            System.out.println("从数据库中查到了部门数据");
            list = depService.findAll();
            //将查到的部门数据写入缓存
            redisUtil.set("depList", list, 6000);
        }
        JsonResult result = new JsonResult();
        result.setHttpCode(200);
        result.setData(list);
        return result;
    }
}
